package com.yh.autobio.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yh.autobio.AppConfig;
import com.yh.autobio.AppContext;
import com.yh.autobio.R;
import com.yh.autobio.api.ApiInterface;
import com.yh.autobio.api.ErrorHandler;
import com.yh.autobio.api.RetrofitSingleton;
import com.yh.autobio.base.BaseFragment;
import com.yh.autobio.common.ACache;
import com.yh.autobio.common.FullyLinearLayoutManager;
import com.yh.autobio.common.PLog;
import com.yh.autobio.common.StringUtils;
import com.yh.autobio.common.UIHelper;
import com.yh.autobio.component.dialog.DialogHelp;
import com.yh.autobio.gddb.gbmanager.BackMatManager;
import com.yh.autobio.gddb.gbmanager.MatHeadManager2;
import com.yh.autobio.modules.adatper.InvoiceDetailAdapter;
import com.yh.autobio.modules.bean.CM;
import com.yh.autobio.modules.bean.CustPhone;
import com.yh.autobio.modules.bean.InvoiceBean;
import com.yh.autobio.modules.bean.InvoiceBody;
import com.yh.autobio.modules.bean.InvoiceHead;
import com.yh.autobio.modules.bean.InvoicePrintBean;
import com.yh.autobio.modules.bean.InvoiceSubBean;
import com.yh.autobio.modules.bean.MatSubBean;
import com.yh.autobio.modules.bean.MessaageEvenBus;
import com.yh.autobio.modules.bean.PackingEntryBean;
import com.yh.autobio.modules.bean.ProductBean;
import com.yh.autobio.modules.bean.Result;
import com.yh.autobio.modules.bean.SimpleBackPage;
import com.yh.autobio.modules.recycleviewutil.RecycleViewDivider;
import com.yh.autobio.modules.ui.empty.EmptyLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.yh.autobio.AppConfig.SCN_CUST_ACTION_SCODE;

/**
 * Created by john on 2018/3/5 0005. 16:14
 */

public class InvoiceDetailFragment extends BaseFragment {
    @InjectView(R.id.recycleview)
    RecyclerView recycleview;
    @InjectView(R.id.swiperefreshlayout)
    SwipeRefreshLayout swiperefreshlayout;
    @InjectView(R.id.error_layout)
    EmptyLayout errorLayout;
    private InvoiceDetailAdapter adapter;
    private InvoiceBean data;
    private ArrayList<ProductBean> products;
    private boolean isPrint;


    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                handleOtherText(message);//扫描处理逻辑
            } else if ("com.scott.ok".equals(intent.getAction())) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "打印成功!", Snackbar.LENGTH_SHORT).show();
            }
        }
    };
    private LinearLayoutManager layoutManager;
    private ArrayList<ProductBean> subBeans;
    private ArrayList<Integer> caseNum;
    private ArrayList<InvoicePrintBean> printBeans;
    private String userId;
    private AlertDialog dialogShow;
    private AlertDialog dialogShow2;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_base_recycleview, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void onDestroy() {
        // 解绑
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe
    public void onEvent(MessaageEvenBus messge) {
        if (messge.isSuccess())
            Snackbar.make(recycleview, "不要着急，请耐心等待打印结果", Snackbar.LENGTH_SHORT).show();
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        setHasOptionsMenu(true);
        EventBus.getDefault().register(this);
        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        intentFilter.addAction("com.scott.ok");
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);
        swiperefreshlayout.setColorSchemeResources(
                R.color.swiperefresh_color1, R.color.swiperefresh_color2,
                R.color.swiperefresh_color3, R.color.swiperefresh_color4);

        swiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // TODO: 2016/8/3 下拉刷新
                initData();
            }
        });
        adapter = new InvoiceDetailAdapter(mActivity);
        adapter.setOnItemLongClickListener(new InvoiceDetailAdapter.OnItemLongClickListener() {
            @Override
            public void OnItemLong(View view, final int position) {
//                System.out.println(position);
//                view.setBackgroundColor(Color.RED);
                ProductBean bean = products.get(position - 1);
                ArrayList<ProductBean> temp = new ArrayList<>();
                for (int i = 0; i < products.size(); i++) {
                    ProductBean bean1 = products.get(i);
                    if (bean.getFNumber_s() != null && bean1.getFNumber_s() != null) {
                        if (bean.getFNumber_s().equals(bean1.getFNumber_s())) {
                            temp.add(bean1);
                        }
                    }
//                    else{
//                        Snackbar.make(mActivity.getWindow().getDecorView(), "请初始化产品条码信息！", Snackbar.LENGTH_SHORT).show();
//                    }
                }
                if (temp.size() > 1) {//说明该产品存在多行
                    DialogHelp.getConfirmDialog(mActivity, "确定选择: " + bean.getFEntryName() + " (" + bean.getFBatchNo() + ") 批次么?", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            for (int j = 0; j < products.size(); j++) {
                                if (j == position - 1) {
                                    products.get(position - 1).setChecked(true);
                                } else {
                                    products.get(j).setChecked(false);
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }).show();
                } else if (temp.size() == 1) {////说明该产品只有一行，不需要长按处理
//                    Snackbar.make(mActivity.getWindow().getDecorView(), "请初始化产品条码信息！", Snackbar.LENGTH_SHORT).show();
                }
            }
        });

        layoutManager = new LinearLayoutManager(mActivity);
        //设置布局管理器
        recycleview.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
//        layoutManager.setOrientation(layoutManager.VERTICAL);
        //设置增加或删除条目的动画
        recycleview.setItemAnimator(new DefaultItemAnimator());
        recycleview.addItemDecoration(new RecycleViewDivider(mActivity, LinearLayoutManager.VERTICAL, 5, Color.BLACK));
    }

    @Override
    public void initData() {
        super.initData();
        userId = AppContext.getInstance().getProperty("user.id");
//        userId = AppContext.getInstance().getCurrentUser().getId();
        printBeans = new ArrayList<>();
        printBeans = (ArrayList<InvoicePrintBean>) ACache.get(mActivity).getAsObject(userId);
        data = (InvoiceBean) getArguments().getSerializable("ITEM");
        String fbillno = data.getFbillno();
        showWaitDialog();
        RetrofitSingleton.getApiService(mActivity).
                FCodeAll(fbillno)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Itemobserver);
        adapter.setData(data);
        recycleview.setAdapter(adapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            mActivity.unregisterReceiver(mSamDataReceiver);
        } catch (Exception ex) {
        }
        ButterKnife.reset(this);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.box_menu, menu);
//        if (isPrint) {
//            MenuItem item = menu.getItem(0);
//            item.setVisible(false);
//        } else {
//            MenuItem item = menu.getItem(1);
//            item.setVisible(false);
//            isPrint = false;
//        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.btn_box:
//                Bundle bundle = new Bundle();
//                bundle.putSerializable("PRODUCTS",products);
//                UIHelper.showSimpleBack(mActivity, SimpleBackPage.INVOICEPRO,bundle,"扫描产品");
                boolean isZero = true;
                List<ProductBean> subProducts = adapter.getProducts();
                subBeans = new ArrayList<>();
                if (subProducts==null||subProducts.size()==0){
                    Snackbar.make(mActivity.getWindow().getDecorView(), "装箱完成！", Snackbar.LENGTH_SHORT).show();
                    return true;
                }
                for (int i = 0; i < subProducts.size(); i++) {
                    if (subProducts.get(i).getFDoneNumber() > 0) {
                        isZero = false;
                        subBeans.add(subProducts.get(i));
                    }
                }

                if (!isZero) {//至少扫描一种物料，允许提交

                    ArrayList<ProductBean> temp = new ArrayList<>();
                    for (int i = 0; i < subBeans.size(); i++) {//判断箱数，只有一个产品存在箱数，或者所有产品都没有箱数才允许提交
                        ProductBean productBean = subBeans.get(i);
                        if (productBean.getFBoxNum() > 0) {
                            temp.add(productBean);
                        }
                    }
                    if (temp.size() > 1) {
                        Snackbar.make(mActivity.getWindow().getDecorView(), "至多一个产品填写箱数！", Snackbar.LENGTH_SHORT).show();
                        return true;
                    } else if (temp.size() == 1 && subBeans.size() > 1) {
                        Snackbar.make(mActivity.getWindow().getDecorView(), "填写箱数时，只允许装箱一种产品！", Snackbar.LENGTH_SHORT).show();
                        return true;
                    } else if (temp.size() == 1 && subBeans.size() == 1) {
                        ProductBean bean = temp.get(0);
                        int doneNumber = bean.getFDoneNumber();
                        int boxNum = bean.getFBoxNum();
                        if (doneNumber / boxNum <= 0 || doneNumber % boxNum != 0) {
                            Snackbar.make(mActivity.getWindow().getDecorView(), "装箱数量必须是箱数的整数倍！", Snackbar.LENGTH_SHORT).show();
                            return true;
                        }
                    }
                    ArrayList<InvoiceBody> subBody = new ArrayList<>();
                    for (int i = 0; i < subBeans.size(); i++) {
                        ProductBean productBean = subBeans.get(i);
                        InvoiceBody body = new InvoiceBody();
                        body.setFBatchNo(productBean.getFBatchNo());
                        body.setFBase(productBean.getFItemId());
                        body.setFBase1(productBean.getFunitId());
                        body.setFEntryID_SRC(productBean.getFentryId());
                        body.setFQty(productBean.getFDoneNumber() + "");
                        body.setFID_SRC(data.getId());
                        body.setFBoxNum(productBean.getFBoxNum());
                        subBody.add(body);
                    }
                    String id=AppContext.getInstance().getProperty("user.id");
//                    String id = AppContext.getInstance().getCurrentUser().getId();
                    InvoiceHead head = new InvoiceHead();
                    head.setFBillNo(data.getFbillno());
                    head.setFBiller(id);
                    head.setFDate(data.getFDate().split("T")[0]);
                    head.setForganiztion(data.getFOrganizations());
                    head.setFAddress(data.getFReceives());
                    showWaitDialog();
                    InvoiceSubBean matSubBean = new InvoiceSubBean();
                    matSubBean.setBodyList(subBody);
                    matSubBean.setHeadDetail(head);
                    Gson gson = new Gson();
                    String json = gson.toJson(matSubBean);
                    String token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
                    CM cm = new CM();
                    cm.setToken(token);
                    cm.setData(json);

//                    RetrofitSingleton.getApiService(mActivity).
//                            SaleMethodAll("",1,12)
//                            .flatMap(new Func1<List<CustPhone>, Observable<Result>>() {
//                                @Override
//                                public Observable<Result> call(List<CustPhone> custPhones) {
//                                    return RetrofitSingleton.getApiService(mActivity).PickSubmitZxd(new CM());
//                                }
//                            })
//                            .subscribeOn(Schedulers.io())
//                            .observeOn(AndroidSchedulers.mainThread())
//                            .subscribe(observer);

                    RetrofitSingleton.getApiService(mActivity).
                            PickSubmitZxd(cm)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(observer);

                } else {
                    Snackbar.make(mActivity.getWindow().getDecorView(), "请装箱！", Snackbar.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_print:
                print2();
//                print();
                break;
        }



        return super.onOptionsItemSelected(item);
    }

    private void print2() {
        try {
            printBeans = (ArrayList<InvoicePrintBean>) ACache.get(mActivity).getAsObject(userId);
            if (printBeans == null || printBeans.size() == 0) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "还未装箱，无法打印!", Snackbar.LENGTH_SHORT).show();
                return;
            }
//            设置的ip打印地址
            String set_ip = AppContext.getInstance().getProperty("set_ip");

            for (int i = 0; i < printBeans.size(); i++) {
                if (!StringUtils.isEmpty(set_ip)) {
                    printBeans.get(i).getHeadDetail().setHostUrl("http://" + set_ip + "/CLodopfuncs.js");
                } else {
                    printBeans.get(i).getHeadDetail().setHostUrl("http://192.168.1.9:8000/CLodopfuncs.js");
                }
            }

//            InvoicePrintBean matSubBean = new InvoicePrintBean();
//
//            matSubBean.setBodyList(subBeans);
//            matSubBean.setHeadDetail(data);
//            matSubBean.setBoxsCount(caseNum);
//            String s1 = new Gson().toJson(matSubBean).toString();
            String s1 = new Gson().toJson(printBeans).toString();

//            ACache.get(mActivity).remove(userId);
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("fB", s1);
            intent.putExtras(bundle);
            UIHelper.showSimpleBack(mActivity, SimpleBackPage.WEB, bundle, "打印预览");
        } catch (Exception e) {
        }

    }

    private void print() {
        final WebView webView = new WebView(getActivity());
        WebSettings settings = webView.getSettings();
        webView.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                InvoicePrintBean matSubBean = new InvoicePrintBean();
                matSubBean.setBodyList(subBeans);
                matSubBean.setHeadDetail(data);
                String s1 = new Gson().toJson(matSubBean);
                webView.loadUrl("javascript:showAndroid('" + s1 + "');");
                createWebPrintJob(view);
            }
        });
// 设置 缓存模式
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.loadUrl("file:///android_asset/print2.html");
    }

    private void createWebPrintJob(WebView webView) {

        // Get a PrintManager instance
        PrintManager printManager = (PrintManager) getActivity()
                .getSystemService(Context.PRINT_SERVICE);

        // Get a print adapter instance
        PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();

        // Create a print job with name and adapter instance
        String jobName = getString(R.string.app_name) + " Document";
        PrintJob printJob = printManager.print(jobName, printAdapter,
                new PrintAttributes.Builder().build());

        // Save the job object for later status checking
//        mPrintJobs.add(printJob);
    }

    private void handleOtherText(String text) {
        boolean isSame = false;
        if (products != null && products.size() > 0) {
            for (int i = 0; i < products.size(); i++) {
                ProductBean productBean = products.get(i);
                if (text.equals(productBean.getFNumber_s())) {//判断扫描产品是否在清单内，再去判断是否存在多行
                    ArrayList<ProductBean> temps = new ArrayList<>();
                    for (int j = 0; j < products.size(); j++) {
                        final ProductBean bean = products.get(j);
                        if (text.equals(bean.getFNumber_s())) {
                            if (bean.isChecked()) {
                                String fWillNum = bean.getFWillNum();
                                int i1 = (int)Double.parseDouble(fWillNum);
                                if (i1>products.get(j).getFDoneNumber()){
                                    products.get(j).setFDoneNumber(products.get(j).getFDoneNumber() + 1);
                                }else{
                                    Snackbar.make(mActivity.getWindow().getDecorView(),"已达到最大装箱数量！",Snackbar.LENGTH_SHORT).show();
                                    layoutManager.scrollToPositionWithOffset(j + 1, 0);
                                    return;
                                }

                                layoutManager.scrollToPositionWithOffset(j + 1, 0);
                                adapter.notifyItemChanged(j + 1);
                                isSame = true;
                                temps = null;


                                final View view1 = View.inflate(mActivity, R.layout.dialog_change_mat, null);
                                final TextView title = (TextView) view1.findViewById(R.id.tv_title);
                                final TextView batch = (TextView) view1.findViewById(R.id.tv_batch);
                                final TextView num = (TextView) view1.findViewById(R.id.tv_num);
                                final EditText content = (EditText) view1.findViewById(R.id.et_content);
                                content.setInputType(InputType.TYPE_CLASS_NUMBER);//| InputType.TYPE_NUMBER_FLAG_DECIMAL
                                if (0 == bean.getFDoneNumber()) {
                                    content.setText("");
                                    content.setHint("请输入装箱数量");
                                } else {
                                    content.setText(bean.getFDoneNumber() + "");
                                    content.setSelection(content.getText().length());
                                }
                                num.setText(bean.getFWillNum() + "(待装数量)");
                                batch.setText(bean.getFBatchNo() + "  (批次)");
                                title.setText(bean.getFEntryName() + "[" + bean.getFEntryModel() + "]");
                                final int finalI1 = i;
                                //                                    holder.etSl.setText(s);
//                                    holder.etSl.setText("0");
                                if (dialogShow != null && dialogShow.isShowing())
                                    dialogShow.dismiss();
                                dialogShow = DialogHelp.getConfirmDialog(mActivity, view1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        String s = content.getText().toString();
                                        try {
                                            int v = Integer.parseInt(s);
                                            String fWillNum = bean.getFWillNum();
                                            int i1 = (int)Double.parseDouble(fWillNum);
                                            if (i1<v){
                                                Snackbar.make(mActivity.getWindow().getDecorView(),"超出待装数量！",Snackbar.LENGTH_SHORT).show();
                                                  return;
                                            }
                                            products.get(finalI1).setFDoneNumber(v);
//                                    holder.etSl.setText(s);
                                        } catch (Exception e) {
                                            products.get(finalI1).setFDoneNumber(0);
//                                    holder.etSl.setText("0");
                                        }
                                        adapter.notifyItemChanged(finalI1 + 1);
                                    }
                                }, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        products.get(finalI1).setFDoneNumber(0);
                                        adapter.notifyItemChanged(finalI1 + 1);
                                    }
                                }).show();


                                return;
                            } else {

                                temps.add(products.get(j));
                            }
                        }
                    }
                    if (temps.size() > 1) {//同一种产品存在多个
                        for (int j = 0; j < products.size(); j++) {
                            if (text.equals(products.get(j).getFNumber_s())){
                                layoutManager.scrollToPositionWithOffset(j + 1, 0);
                                break;
                            }
                        }
                        DialogHelp.getMessageDialog(mActivity,temps.get(0).getFEntryName() +"存在多个批次，请长按选择批次！").show();

                    } else {//同一种产品只有一个
                        for (int j = 0; j < products.size(); j++) {
                            if (products.get(j).isChecked()) {
                                products.get(j).setChecked(false);
                                adapter.notifyItemChanged(j + 1);
                            }
                        }
                        final ProductBean bean = products.get(i);
                        String fWillNum = bean.getFWillNum();
                        int i1 = (int)Double.parseDouble(fWillNum);
                        if (i1>products.get(i).getFDoneNumber()){
                            products.get(i).setFDoneNumber(products.get(i).getFDoneNumber() + 1);
                        }else{
                            Snackbar.make(mActivity.getWindow().getDecorView(),"已达到最大装箱数量！",Snackbar.LENGTH_SHORT).show();
                            layoutManager.scrollToPositionWithOffset(i + 1, 0);
                            return;
                        }
                        layoutManager.scrollToPositionWithOffset(i + 1, 0);
                        adapter.notifyItemChanged(i + 1);
                        isSame = true;

                        final View view1 = View.inflate(mActivity, R.layout.dialog_change_mat, null);
                        final TextView title = (TextView) view1.findViewById(R.id.tv_title);
                        final TextView batch = (TextView) view1.findViewById(R.id.tv_batch);
                        final EditText content = (EditText) view1.findViewById(R.id.et_content);
                        content.setInputType(InputType.TYPE_CLASS_NUMBER);//| InputType.TYPE_NUMBER_FLAG_DECIMAL
                        if (0 == bean.getFDoneNumber()) {
                            content.setText("");
                            content.setHint("请输入装箱数量");
                        } else {
                            content.setText(bean.getFDoneNumber() + "");
                            content.setSelection(content.getText().length());
                        }
                        final TextView num = (TextView) view1.findViewById(R.id.tv_num);
                        num.setText(bean.getFWillNum() + "(待装数量)");
                        batch.setText(bean.getFBatchNo() + "  (批次)");
                        title.setText(bean.getFEntryName() + "[" + bean.getFEntryModel() + "]");
                        final int finalI = i;
                        //                                    holder.etSl.setText(s);
//                                    holder.etSl.setText("0");
                        if (dialogShow2!=null&&dialogShow2.isShowing())
                            dialogShow2.dismiss();
                        dialogShow2 = DialogHelp.getConfirmDialog(mActivity, view1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String s = content.getText().toString();
                                try {
                                    int v = Integer.parseInt(s);
                                    String fWillNum = bean.getFWillNum();
                                    int i1 = (int)Double.parseDouble(fWillNum);
                                    if (i1<v){
                                        Snackbar.make(mActivity.getWindow().getDecorView(),"超出待装数量！",Snackbar.LENGTH_SHORT).show();
                                        return;
                                    }
                                    products.get(finalI).setFDoneNumber(v);
//                                    holder.etSl.setText(s);
                                } catch (Exception e) {
                                    products.get(finalI).setFDoneNumber(0);
//                                    holder.etSl.setText("0");
                                }
                                adapter.notifyItemChanged(finalI + 1);
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                products.get(finalI).setFDoneNumber(0);
                                adapter.notifyItemChanged(finalI + 1);
                            }
                        }).show();
                    }
                    return;
                }
            }
        }
        if (!isSame) {
            Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描清单物料！", Snackbar.LENGTH_SHORT).show();
        }

    }

    private void updateItem() {

        InvoicePrintBean matSubBean = new InvoicePrintBean();
        matSubBean.setBodyList(subBeans);
        matSubBean.setHeadDetail(data);
        matSubBean.setBoxsCount(caseNum);
        printBeans = (ArrayList<InvoicePrintBean>) ACache.get(mActivity).getAsObject(userId);
        if (printBeans == null)
            printBeans = new ArrayList<>();
        printBeans.add(matSubBean);
        ACache.get(mActivity).put(userId, printBeans);
        data.setCaseNums(caseNum);
        adapter.setData(data);
        String fbillno = data.getFbillno();
        showWaitDialog();
        RetrofitSingleton.getApiService(mActivity).
                FCodeAll(fbillno)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Itemobserver);
    }

    Observer<List<ProductBean>> Itemobserver = new Observer<List<ProductBean>>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
            if (swiperefreshlayout.isRefreshing()) {
                swiperefreshlayout.setRefreshing(false);
            }
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(List<ProductBean> result) {
            hideWaitDialog();
            products = (ArrayList<ProductBean>) result;
            if (result != null && result.size() > 0) {
                adapter.setProducts(result);
            }
            else{
                adapter.setProducts(null);
                adapter.notifyDataSetChanged();
//                adapter.setData(data);
//                recycleview.setAdapter(adapter);
            }
        }
    };

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result.isSuccess()) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "装箱成功!", Snackbar.LENGTH_SHORT).show();
//                isPrint = true;
//                mActivity.invalidateOptionsMenu();
                ArrayList<Double> data = (ArrayList<Double>) result.getData();
                ArrayList<Integer> integers = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    int fs = (int)Math.pow(data.get(i),1);
//                    int fsw = Integer.parseInt(data.get(i)+"");
                    integers.add(fs);
                }
                caseNum = integers;
                updateItem();

//                mActivity.finish();
            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), result.getMessage(), Snackbar.LENGTH_SHORT).show();
            }
        }
    };


}
